from fastapi import Request
from fastapi.responses import JSONResponse
from app.core.exceptions import AITechException, handle_exception
import time

async def error_handler_middleware(request: Request, call_next):
    try:
        start_time = time.time()
        response = await call_next(request)
        process_time = time.time() - start_time
        response.headers["X-Process-Time"] = str(process_time)
        return response
    except Exception as e:
        return JSONResponse(
            status_code=handle_exception(e).status_code,
            content={"detail": str(e)}
        ) 